package cn.lg.soar.cloud.core.config;

import cn.lg.soar.common.util.IpUtil;
import cn.lg.soar.common.util.current.CurrentUser;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * feign调用前设置客户端地址和当前用户
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (attributes != null) {
            javax.servlet.http.HttpServletRequest request = attributes.getRequest();
            requestTemplate.header("User-Agent", request.getHeader("User-Agent"));
            requestTemplate.header(IpUtil.CLIENT_IP, IpUtil.getRemoteIp(request));
            requestTemplate.header(CurrentUser.USER_KEY, request.getHeader(CurrentUser.USER_KEY));
        }
    }

}
